import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_menu/app_config.dart';
import 'package:flutter_menu/biz/order/detail/detail_controller.dart';
import 'package:flutter_menu/biz/order/detail/option/options_dialog.dart';
import 'package:flutter_menu/biz/order/order_controller.dart';
import 'package:flutter_menu/utils/common_utils.dart';
import 'package:flutter_menu/widgets/load_container.dart';
import 'package:get/get.dart';

class PriceController extends GetxController {
  static const priceLengthLimit = 8;

  // 印尼 or 墨西哥
  var isInd = true;

  // 默认价格 后端获取
  num defaultDishPrice = 0;

  // 显示的默认价格
  String get defaultPrice {
    return isInd ? '0' : '0.00';
  }

  // 用户输入价格
  var inputText = '0'.obs;

  void resetPrice() {
    inputText.value = defaultDishPrice.toString();
  }

  void setNewPrice() {
    var tryParse = num.tryParse(inputText.value);
    if (inputText.value != defaultPrice && tryParse != null) {
      var detailController = Get.find<DetailController>();
      detailController.setNewPrice(tryParse);
      Get.back();
      Get.dialog(
        OptionsDialog(),
        transitionCurve: Curves.easeIn,
        transitionDuration: const Duration(milliseconds: 100),
      );
    }
  }

  void onNumberTap(PriceNumberKey type) {
    // 检查输入上限
    if (inputText.value.length + type.label.length > priceLengthLimit) {
      return;
    }

    if (type == PriceNumberKey.dot) {
      // 输入中不能有超过一个小数点
      if (inputText.value.contains('0')) {
        return;
      }
    }

    var label = type.label;
    if (inputText.value == defaultPrice) {
      if (type == PriceNumberKey.dot) {
        inputText.value = inputText.value + label;
      } else if (type != PriceNumberKey.zero &&
          type != PriceNumberKey.doubleZero &&
          type != PriceNumberKey.tripleZero) {
        inputText.value = label;
      }
    } else {
      inputText.value = inputText.value + label;
    }
  }

  void onDeleteTap() {
    if (inputText.value.length > 1) {
      inputText.value =
          inputText.value.substring(0, inputText.value.length - 1);
    } else {
      onClearTap();
    }
  }

  void onClearTap() {
    inputText.value = defaultPrice;
  }

  @override
  void onInit() {
    super.onInit();
    onClearTap();
  }

  @override
  void onClose() {
    super.onClose();
  }
}

enum PriceNumberKey {
  one("1"),
  two("2"),
  three("3"),
  four("4"),
  five("5"),
  six("6"),
  seven("7"),
  eight("8"),
  nine("9"),
  dot("."),
  zero("0"),
  doubleZero("00"),
  tripleZero("000");

  final String label;

  const PriceNumberKey(this.label);
}
